package com.zy.list.create

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.zy.list.ListConstant.ARG_PARENT_ID
import com.zy.list.R

class CreateNewFragment : BottomSheetDialogFragment() {

    private var parentId = 0L

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            parentId = it.getLong(ARG_PARENT_ID)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val view = inflater.inflate(R.layout.dialog_fragment_create_new_layout, container, false)
        view.findViewById<View>(R.id.create_folder).setOnClickListener {
            //新建文件夹
            dismissAllowingStateLoss()
            //展示修改文件夹名称的dialog
            CreateOrModifyTitleFragment.show(parentFragmentManager, 0, parentId)
        }

        view.findViewById<View>(R.id.create_file).setOnClickListener {
            //新建文件
            dismissAllowingStateLoss()
            //展示修改文件名称的dialog
            CreateOrModifyTitleFragment.show(parentFragmentManager, 1, parentId)
        }
        return view
    }

    companion object {

        fun show(parentFragmentManager: FragmentManager, parentId: Long = 0) {
            val ft: FragmentTransaction = parentFragmentManager.beginTransaction()
            val prev: Fragment? = parentFragmentManager.findFragmentByTag("create_new")
            if (prev != null) {
                ft.remove(prev)
            }
            ft.addToBackStack(null)
            val newFragment: DialogFragment = CreateNewFragment().apply {
                arguments = Bundle().apply {
                    putLong(ARG_PARENT_ID, parentId)
                }
            }
            newFragment.show(ft, "create_new")
        }
    }
}